package com.cloudcc.mobile.presenter;

import java.util.List;
import java.util.Stack;

import org.apache.http.Header;

import android.app.Activity;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.LoginEvent;
import com.cloudcc.cloudframe.bus.EventList.ServerUrlEvent;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.async.GsonHttpResponseHandler;
import com.cloudcc.cloudframe.net.model.LoginRequestModel;
import com.cloudcc.cloudframe.plugin.MessageManager;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppConfig;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.UserEngine;
import com.cloudcc.mobile.dao.impl.UserEngineImpl;
import com.cloudcc.mobile.entity.LoginDBModel;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.AESUtils;
import com.cloudcc.mobile.view.main.MainUIActivity;
import com.litesuits.android.async.TaskExecutor;
import com.litesuits.common.utils.HexUtil;
import com.litesuits.common.utils.MD5Util;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;

/**
 * 登录服务的控制器
 * 
 * @author wangzhiqiang
 * @date 2015-7-27 上午10:51:54
 * 
 */
public class LoginPresenter extends BasePresenter {

	private final UserEngine mService;

	public LoginPresenter() {
		super();
		mService = new UserEngineImpl(AppContext.getApp());
	}

	/**
	 * 根据userName获得 应用程序的服务器url
	 * 
	 * @param userName
	 */
	public void getAppUrl(String userName) {
		ServerUrlEvent event = new ServerUrlEvent();
		if (checkNoNet(event)) {
			return;
		}
		if (TextUtils.isEmpty(userName)) {
			event.setOk(false);
			event.setMessage(MessageManager.getInstance().getString(
					R.string.meg_user_error_null));
			EventEngine.post(event);
			return;
		}
		mService.getAppUrl_w(userName, event);
	}

	public void login(String userName, String password) {
		LoginEvent event = new LoginEvent();
		if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
			event.setOk(false);
			event.setMessage(MessageManager.getInstance().getString(
					R.string.meg_user_error_null));
			EventEngine.post(event);
			return;
		}
		if (checkNoNet(event)) {
			return;
		}
		byte[] md5 = MD5Util.md5(password);
		String encodeHexStr = HexUtil.encodeHexStr(md5);
		mService.login_w(userName, encodeHexStr, true, event);
	}

	public void logintiyan(String userName, String password) {
		LoginEvent event = new LoginEvent();
		if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
			event.setOk(false);
			event.setMessage(MessageManager.getInstance().getString(
					R.string.meg_user_error_null));
			EventEngine.post(event);
			return;
		}
		if (checkNoNet(event)) {
			return;
		}
		byte[] md5 = MD5Util.md5(password);
		String encodeHexStr = HexUtil.encodeHexStr(md5);
		mService.login_w(userName, encodeHexStr, false, event);
	}

	/**
	 * 将用户保存到登录记录
	 * 
	 * @param userName
	 *            用户名
	 * @param password
	 *            密码
	 * @param isMD5
	 *            是否是md5加密后的
	 * @param isAuto
	 *            是否自动登录
	 * @param isRemberUser
	 *            是否记住用户名
	 */
	public void saveLoginToHistory(String userName, String password,
			boolean isMD5, boolean isAuto, boolean isRemberUser) {
		LoginDBModel login = new LoginDBModel();
		login.userName = userName;
		login.password = password;
		login.isMD5 = isMD5;
		login.lastLogin = System.currentTimeMillis();
		login.isAutoLogin = isAuto;
		login.isRememberUser = isRemberUser;
		mService.insertOrUpdate(login);
	}

	/**
	 * 获得所有曾经登录的
	 * 
	 * @return
	 */
	public List<LoginDBModel> getAllLogins() {
		return mService.getAll();
	}

	/**
	 * 获得最近登录的帐号
	 * 
	 * @return
	 */
	public LoginDBModel getLastLogin() {
		List<LoginDBModel> logins = mService.getAll();
		if (logins == null | logins.size() == 0) {
			LoginDBModel model = new LoginDBModel();
			model.userName = "";
			model.password = "";
			return model;
		}
		return logins.get(0);
	}

	/**
	 * 获得解密后的 用户名密码
	 * 
	 * @return 返回一个长度为3 的 一位数组<br>
	 *         [0]: 标志位 判断是不是 true 如果是 false 表示解析的时候失败 或者 获取的用户名密码为空<br>
	 *         [1]:username [2]:password 明文
	 */
	public String[] getDecryptedLogin() {
		// 数组第一位 是标志位 :为空的时候 表示失败
		String[] array = new String[] { String.valueOf(false),
				StringUtils.EMPTY, StringUtils.EMPTY };

		LoginDBModel login = getLastLogin();

		if (StringUtils.isBlank(login.userName)
				|| StringUtils.isBlank(login.password)) {
			return array;
		}
		// 通过jni获取c代码里面保存的密码 然后解密出来
		String dePassword = AESUtils.getDePassword(login.password);
		if (TextUtils.isEmpty(dePassword)) {// 解密失败
			return array;
		}
		array[0] = String.valueOf(true);
		array[1] = String.valueOf(login.userName);
		array[2] = String.valueOf(dePassword);
		return array;

	}

	/**
	 * 删除一条记录
	 * 
	 * @param userName
	 * @return
	 */
	public boolean delLogin(String userName) {
		return mService.delete(userName);
	}

	/**
	 * 判断 当前 上一次更新是不是 大于 seesion失效时间
	 * 
	 * @return
	 */
	public boolean shouldRefreshBinding() {
		long nowMillis = SystemClock.elapsedRealtime();
		long during = nowMillis
				- RunTimeManager.getInstance().getLastLoginTime();
		Stack<Activity> activityStack = com.cloudcc.mobile.AppManager
				.getInstance().getActivityStack();
		boolean iscan = false;
		for (Activity activity : activityStack) {
			if (activity != null && activity instanceof MainUIActivity) {
				iscan = true;
			}
		}
		if (during > AppConfig.REFRESHBINDINGDURING && iscan) {
			return true;
		}
		return false;
	}

	private boolean refreshBindingImpl() {
		String[] login = new LoginPresenter().getDecryptedLogin();
		boolean b = Boolean.parseBoolean(login[0]);
		if (!b) {
			return false;
		}
		RequestParams params = new RequestParams();
		params.put("serviceName", "clogin");
		params.put("userName", login[1]);
		byte[] md5 = MD5Util.md5(login[2]);
		String encodeHexStr = HexUtil.encodeHexStr(md5);
		params.put("password", encodeHexStr);
		params.put("isMD5", true);
		Log.d("---url",UrlManager.getInterfaceUrl()+"?serviceName=clogin&isMD5=true&password"+encodeHexStr+"&userName="+login[1]);
		SyncHttpClient client = new SyncHttpClient(80, 443);
		final String[] result = new String[] { String.valueOf(true) };
		client.post(UrlManager.getInterfaceUrl(), params,
				new GsonHttpResponseHandler<LoginRequestModel>(
						LoginRequestModel.class, null) {

					@Override
					public void onSuccess(LoginRequestModel t) {
						RunTimeManager.setAppBinding(t.binding);
						RunTimeManager.getInstance().setLoginTime(
								SystemClock.elapsedRealtime());
						result[0] = "true";
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							String responseString, Throwable throwable) {
						super.onFailure(statusCode, headers, responseString,
								throwable);
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBytes, Throwable throwable) {
						super.onFailure(statusCode, headers, responseBytes,
								throwable);
					}

					@Override
					public void onFailure(ErrorInfo error) {
						result[0] = "false";
					}

					@Override
					public void onLoginInvalid() {
						result[0] = "false";
					}
				});
		return Boolean.parseBoolean(result[0]);

	}

	public void refreshBinding() {
		if (shouldRefreshBinding()) {
			TaskExecutor.start(new Runnable() {
				private int retryNum = 0;

				@Override
				public void run() {
					while (retryNum < 2) {
						if (refreshBindingImpl()) {
							retryNum = 3;
							LogUtils.d("loginimpl", "刷新成功");
						} else {
							retryNum++;
							LogUtils.d("loginimpl", "刷新重试" + retryNum);
						}
					}
					LogUtils.d("loginimpl", "刷新结束");

				}
			});
		}

	}

}
